﻿using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Text;

namespace WorkFlowCore.Common.EventBus
{
    /// <summary>
    /// 全局静态事件帮助类，便于在其它非注入渠道发起事件
    /// </summary>
    public class EventBusManager
    {
        private static IServiceProvider serviceProvider;
        internal static void Init(IServiceProvider serviceProvider)
        {
            EventBusManager.serviceProvider = serviceProvider;
        }

        public IEventBus Instance()
        {
            return (IEventBus)serviceProvider.GetService(typeof(IEventBus));
        }

        public void Trigger<TData>(TData data) where TData:BaseEventData
        {
            if (data == null) return;
            var services =serviceProvider.GetServices<IEventBus>();
            foreach (var service in services)
            {
                try
                {
                    service.Trigger(data); 
                }
                catch (Exception ex)
                {
                    Console.Error.WriteLine(ex.ToString());
                }
            }
        }
    }
}
